package cc.bukkitPlugin.banitem.command.analyse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.BlockIterator;

import cc.bukkitPlugin.banitem.BanItem;
import cc.bukkitPlugin.banitem.CFG;
import cc.bukkitPlugin.banitem.command.AParamCommand;
import cc.bukkitPlugin.banitem.util.BINMSUtil;
import cc.bukkitPlugin.util.nbt.NBTUtil;

public class ParamNBTLabel extends AParam{

    public ParamNBTLabel(BanItem pPlugin,AnalyseMan pAnalyor){
        super(pPlugin,pAnalyor);
        this.mLabels=new String[]{"nl","nbtlabel"};
    }

    @Override
    public AnalyseResult handle(CommandSender pSender,AnalyseResult pCmdParam,String pArg){
        pCmdParam.mNBTLabel=pArg;
        return pCmdParam.buildSuccess();
    }

    @Override
    public ArrayList<String> getHelp(){
        ArrayList<String> help=new ArrayList<>();
        help.add(CFG.cmd_color+"  "+Arrays.toString(this.mLabels));
        help.add(CFG.help_color+"    设置配置的物品的NBT标签");
        help.add(CFG.help_color+"    Tab补全会尝试读取当前手上物品的NBT标签");
        return help;
    }

    @Override
    public ArrayList<String> tabComplete(CommandSender pSender,AParamCommand pCommand,String[] pArgs){
        ArrayList<String> list=new ArrayList<>();
        if(pArgs==null||pArgs.length==0)
            return list;
        String[] params=pArgs[pArgs.length-1].split(":",2);
        String tLabel=params[0]+":";
        // Tab补全时不需要做严格的检查
        ItemStack checkItem=null;
        Map<String,Object> tNBTContents=null;
        if(pSender instanceof Player){
            Player tPlayer=(Player)pSender;
            checkItem=tPlayer.getItemInHand();
            if(checkItem!=null&&checkItem.getType()!=Material.AIR){
                tNBTContents=NBTUtil.getNBTTagMapFromItem(checkItem);
            }else{
                Block tblock=null;
                Iterator<Block> itr=new BlockIterator(tPlayer,8);
                while(itr.hasNext()){
                    tblock=itr.next();
                    if(tblock!=null&&tblock.getType()!=Material.AIR)
                        break;
                }
                tNBTContents=BINMSUtil.getNBTTagMapFromBlock(tblock);
            }
        }
        if(tNBTContents==null||tNBTContents.isEmpty())
            return list;
        String part="";
        if(params.length==2)
            part=params[1].toLowerCase();
        for(String sKey : tNBTContents.keySet()){
            if(sKey.toLowerCase().startsWith(part)){
                list.add(tLabel+sKey);
                if(list.size()>=100)
                    return list;
            }
        }
        return list;
    }

}
